package com.xzg.erp.system.entity.dto;

import cn.hutool.core.collection.CollUtil;
import com.xzg.erp.common.Constants;
import com.xzg.erp.system.entity.SysOrganization;
import lombok.Data;

import java.util.*;
import java.util.stream.Collectors;

@Data
public class OrgTreeDto {

    private Integer id;

    private String name;

    private Integer parentId;

    private List<OrgTreeDto> children;

    // 将对象列表转换为树结构
    public static List<OrgTreeDto> buildTree(List<SysOrganization> orgs) {

        Map<Integer, List<SysOrganization>> pGroup = orgs.stream().collect(Collectors.groupingBy(SysOrganization::getParentId));

        List<SysOrganization> parent = pGroup.get(Constants.PARENT_ID);

        if (CollUtil.isEmpty(parent)) {
            return Collections.emptyList();
        }
        
        return doBuildTree(parent,pGroup);
    }

    private static List<OrgTreeDto> doBuildTree(List<SysOrganization> parent, Map<Integer, List<SysOrganization>> pGroup) {
        return parent.stream().map(org->{
            OrgTreeDto dto = new OrgTreeDto();
            dto.setId(org.getId());
            dto.setName(org.getName());
            dto.setParentId(org.getParentId());
            List<SysOrganization> subGroup = pGroup.get(dto.getId());
            if (CollUtil.isNotEmpty(subGroup)) {
                dto.setChildren(doBuildTree(subGroup,pGroup));
            }else {
                dto.setChildren(Collections.emptyList());
            }
            return dto;
        }).collect(Collectors.toList());
    }
}
